package com.jackrain.clouddata.sys.Listenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.clouddata.oms.dao.SaleDao;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.web.query.QueryEngine;
import com.jackrain.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Created by nathan on 2017/8/15.
 */
@Component("com.jackrain.clouddata.sys.Listenter.SaleMessageProcess")
@Slf4j
public class SaleMessageProcess implements MessageProcess{


    @Override
    public void process(Object paramObject, String tag) throws Exception{
        SaleDao saleDao = ApplicationContextHandle.getBean(SaleDao.class);

        JSONArray paramArray = JSONArray.parseArray(JSON.toJSONString(paramObject,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));
        try {
            if (paramArray != null && paramArray.size() > 0) {
                insertitem(paramArray, tag, saleDao);
            }
        }catch (Exception e){
            throw e;
        }
    }

    private void insertitem(JSONArray jsonArray,String tag,SaleDao saleDao) throws Exception {
        //根据tag获取公司ID
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        JSONArray hotArray = new JSONArray();
        for (int i =0;i< jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONObject mainJson = jsonObject.getJSONObject("value");
            JSONArray itemArray = jsonObject.getJSONArray("item");
            //获取主表名称
            String mainName = jsonObject.getString("name");
            try {
                saleDao.execute(mainJson,itemArray,clientId);
                WebUtils.CallInterface(clientId,"OMS_M_SALE",tag,jsonObject);
                hotArray.add(jsonObject);
            }catch (Exception e){
                e.printStackTrace();
            }
        }




    }


}
